// pages/my/myfriend/myfriend.js
var app = getApp();
Page({
  data: {
    portrait: '',//用户头像
    friendList: [],
    total_friend_stars: 0,
    total_count: 0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getFriendListOptions();
  },
  onShow: function (options) {
    this.getFriendListOptions();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取加入的好友和赚到的信息
    this.getFriendCount();
    this.getMyInfo();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    var shareType;
    var path = '/pages/login/login';
    if (e && e.from == 'button') {
      shareType = e.target.dataset.type;
      if (shareType == 'user') {
        path += '?token=' + this.userShareToken;
      }
    }
    return {
      title: '【' + this.myinfo.user_name + '】，0元拼团，1分钱不要，全场包邮>>',
      path: path,
      imageUrl: '../../../style/img/share.png',
      success: () => {
      }
    }
  },

  getFriendListOptions: function () {
    var options = {
      list_id: 'friendList',
      url: '/api/index.php?app=friend&act=my_list',
    }
    var scrollListHeight = app.globalData.pageHeight;
    this.setData({
      friendListOptions: options,
      scrollListHeight: scrollListHeight
    })
  },

  //获取个人用户具体信息
  getMyInfo: function () {
    app.getUserInfo((res) => {
      this.myinfo = res;
      this.setData({
        portrait: res.portrait
      })
      this.getShareToken();
    })
  },
  /**
   * 生成分享码
   */
  getShareToken: function () {
    app.Ajax({
      method: 'POST',
      url: '/api/index.php?app=home&act=token',
      data: {
        type: 0,
        page: 'pages/my/myfriend/friend_list/friend_list?user_id=' + this.myinfo.user_id,
      },
      success: (res) => {
        this.userShareToken = res.token;
      }
    })
  },

  //加载数据
  loadMoreData: function (e) {
    if (e.detail.data.length > 0) {
      let resArr = [];
      let hash = {};
      for (let item of e.detail.data) {
        item.sort = item.sort.toUpperCase();
        if (!hash[item.sort]) {
          hash[item.sort] = true;
          resArr.push({
            titleLetter: item.sort.toUpperCase(),
            children: [],
          })
        }
      }
      for (let item of e.detail.data) {
        for (let row of resArr) {
          if (item.sort.toUpperCase() == row.titleLetter) {
            row.children.push(item);
          }
        }
      }
      this.setData({
        friendList: resArr
      })
    }
  },


  //获取好友的数量和赚到的星星
  getFriendCount: function () {
    app.Ajax({
      url: '/api/index.php?app=friend&act=my_list',
      success: (res) => {
        this.setData({
          total_friend_stars: res.total_friend_stars,
          total_count: res.total_count
        })
      },
      fail: (err) => {

      }
    })
  },

})